﻿using DB.Main;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Services;
using WebApplication1.Utils;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AlarmController : ControllerBase
    {
        public AlarmService AlarmService { get; set; }  
        public AlarmController()
        {
            AlarmService = new AlarmService();  
        }
        
        /// <summary>
        /// 插入报警数据
        /// </summary>
        /// <param name="TerminalId">设备Id</param>
        /// <param name="AlarmCode">报警Code</param>
        /// <param name="Value">报警数值</param>
        /// <param name="Content">报警详细信息</param>
        [HttpGet]
        public void InsertAlarmValue(string TerminalId,int AlarmCode,decimal Value,string Content)
        {
            var model = new t_Alarm()
            {
                TerminalId = TerminalId,
                deviceId = Convert.ToInt64(TerminalId,16),
                AlarmCode = AlarmCode,
                Value = Value,
                Content = Content,
                CreateTime = DateTime.Now,
                StartTime = DateTime.Now,
                Flag = -1,
                Status = 1,
            };
            MyLogHelper.Debug($"报警数据插入{model.TerminalId}");
            AlarmService.InsertAlarm(model);
        }

        /// <summary>
        /// 设备消警
        /// </summary>
        [HttpGet]
        public void CancelAlarm(string TermianlId)
        {
            AlarmService.CancelAlarm(TermianlId);
        }

        /// <summary>
        /// 发送短信信息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="msg"></param>
        [HttpGet]
        public void SendPhoneMsg(string phone,string msg)
        {
            msg = "【新图维】" + msg;
            MyLogHelper.Debug($"短信发送:phone[{phone}],msg[{msg}]");

            Task.Run(async () =>
            {
                HttpClient client = new HttpClient();

                var res = await client.GetStringAsync($"http://www.szlslxx.com:8011/sms/SendMsg?userId=zjxtw1&password=32a077f226a45c3ea1b40270a17dcea6&mobile={phone}&content={msg}");
                MyLogHelper.Debug($"phone[{phone}]:" +res);
            });
        }
        /// <summary>
        /// 获取报警状态
        /// </summary>
        /// <param name="TerminalId"></param>
        /// <returns></returns>
        [HttpGet]
        public bool GetAlarmFlag(string TerminalId)
        {
            var deivceId = Convert.ToInt64(TerminalId, 16);
            var lists = AlarmService.MysqlSugar.Main.Queryable<t_Alarm>()
                .Where(t=>t.deviceId == deivceId && t.Flag == -1)
                .ToList();

            if(lists.Count == 0)
            {
                return false;
            }

            return true;
        }
    }
}
